﻿using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Framework
{
    /// <summary>
    /// ab汇总信息封装
    /// 支持sbp兼容模式输出的汇总信息
    /// </summary>
    public class AllManifest
    {
        internal Dictionary<string, string[][]> abLookTab;
        private static readonly string[] EmptyDepsArray = { };
        private static readonly string[][] EmptyDepsList = { EmptyDepsArray, EmptyDepsArray };

        public AllManifest(AssetItem assetItem)
        {
            var data = assetItem.DataAsset;
            data = UnityZipUtil.UnzipBuffer(data);
            abLookTab = new Dictionary<string, string[][]>();
            using (MemoryStream memoryStream = new MemoryStream(data))
            {
                using (BinaryReader binaryReader = new BinaryReader(memoryStream))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    while (memoryStream.Position < memoryStream.Length)
                    {
                        string abName = string.Intern(binaryReader.ReadString());
                        int allDepCount = binaryReader.ReadInt32();

                        if (allDepCount == 0)
                        {
                            abLookTab[abName] = EmptyDepsList;
                            binaryReader.ReadInt32();
                            continue;
                        }
                        string[] allDeps = new string[allDepCount];
                        for (int idx = 0; idx < allDepCount; idx++)
                        {
                            allDeps[idx] = binaryReader.ReadString();
                        }

                        int directDepCount = binaryReader.ReadInt32();
                        string[] directDeps = new string[directDepCount];
                        for (int idx = 0; idx < directDepCount; idx++)
                        {
                            directDeps[idx] = binaryReader.ReadString();
                        }

                        abLookTab[abName] = new string[][] { allDeps, directDeps };
                    }
                }
            }

            Debug.Log("init all manifest done");
        }

        public string[] GetAllDependencies(string abName)
        {
            if (abLookTab.ContainsKey(abName))
            {
                return abLookTab[abName][0];
            }
            Logger.LogError($"GetAllDependencies abName:{abName} is not in manifest info!");
            return EmptyDepsArray;
        }

        public string[] GetDirectDependencies(string abName)
        {
            if (abLookTab.ContainsKey(abName))
            {
                return abLookTab[abName][1];
            }
            Logger.LogError($"GetDirectDependencies abName:{abName} is not in manifest info!");
            return EmptyDepsArray;
        }
    }
}